package com.xuebang.admin.web;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.io.Files;

public class StaticFileFilter implements Filter {
	private final static String DEFAULT_CONTENT_TYPE = "text/plain";
	private final static Map<String, String> mimeTypes = new HashMap<String, String>();

	{
		mimeTypes.put("txt", "text/plain");
		mimeTypes.put("html", "text/html");
		mimeTypes.put("css", "text/css");
		mimeTypes.put("js", "application/x-javascript");
		mimeTypes.put("gif", "image/gif");
		mimeTypes.put("png", "image/png");
		mimeTypes.put("jpg", "image/jpeg");
		mimeTypes.put("jpeg", "image/jpeg");
		mimeTypes.put("xml", "text/xml");
		mimeTypes.put("ico", "image/x-icon");
		mimeTypes.put("svg", "image/svg+xml");
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		String path = req.getRequestURI();
		String contextPath =req.getContextPath();
		String prmPath = path.substring(contextPath.length()+1, path.length());
		//String realPath = req.getServletContext().getRealPath(path);
		String realPath = req.getSession().getServletContext().getRealPath(prmPath);
		File file = new File(realPath);
		if (file.isFile() && file.exists()) {
			HttpServletResponse resp = (HttpServletResponse) response;

			long length = file.length();
			resp.setContentLength((int) length);
			String contentType = getContentType(file);
			resp.setContentType(contentType);
			
			Files.copy(file, response.getOutputStream());
			response.getOutputStream().flush();
		} else {
			chain.doFilter(request, response);
		}

	}

	private String getContentType(File file) {
		String name = file.getName();
		int idx = name.lastIndexOf(".");
		String suffix = "";
		if (idx != -1) {
			suffix = name.substring(idx + 1);
		}
		String contentType = mimeTypes.get(suffix);
		if (contentType == null) {
			contentType = DEFAULT_CONTENT_TYPE;
		}
		return contentType + "; charset=UTF-8";
	}

	@Override
	public void destroy() {
	}

}
